package com.rfid.project.web;

import java.text.DateFormat;
import java.util.List;
import java.util.Date;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ui.Model;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.data.domain.Page;

import biz.appframe.PageJsonBean;

import com.rfid.project.exception.CannotDelException;
import com.rfid.project.exception.CannotUpdateException;
import com.rfid.project.model.Customer;
import com.rfid.project.model.Department;
import com.rfid.project.model.ProjectMember;
import com.rfid.project.model.ProjectReportFrequency;
import com.rfid.project.model.ProjectSource;
import com.rfid.project.model.ProjectType;
import com.rfid.project.service.CustomerService;
import com.rfid.project.service.DepartmentService;
import com.rfid.project.service.ProcessStatus;
import com.rfid.project.service.ProjectFinishApplyService;
import com.rfid.project.service.ProjectMemberService;
import com.rfid.project.service.ProjectReportFrequencyService;
import com.rfid.project.service.ProjectSourceService;
import com.rfid.project.service.ProjectTypeService;
import com.rfid.project.model.People;
import com.rfid.project.service.PeopleService;
import com.rfid.project.model.Project;
import com.rfid.project.service.ProjectService;
import com.rfid.project.model.ProjectMemberType;
import com.rfid.project.service.ProjectMemberTypeService;
import com.rfid.project.util.NumberUtil;

@Controller
public class ProjectMemberController {

	private static final Logger logger = LoggerFactory.getLogger(ProjectMemberController.class);

	@Autowired
	private ProjectMemberService projectMemberService;

	@Autowired
	private ProjectService projectService;

	@Autowired
	private ProjectMemberTypeService projectMemberTypeService;

	@Autowired
	private PeopleService peopleService;

	@Autowired
	private DepartmentService departmentService;

	@Autowired
	private ProjectTypeService projectTypeService;

	@Autowired
	private ProjectSourceService projectSourceService;

	@Autowired
	private CustomerService customerService;

	@Autowired
	private ProjectReportFrequencyService projectReportFrequencyService;

	@Autowired
	private ProjectFinishApplyService projectFinishApplyService;

	@RequestMapping(value = "/myProjects")
	public String myProjects(HttpServletRequest request,
			HttpServletResponse response, Model model) {
		List<Department> departments = departmentService.findAll();
		model.addAttribute("departments", departments);

		List<ProjectType> projectTypes = projectTypeService.findAll();
		model.addAttribute("projectTypes", projectTypes);

		List<ProjectSource> projectSources = projectSourceService.findAll();
		model.addAttribute("projectSources", projectSources);

		List<Customer> customers = customerService.findAll();
		model.addAttribute("customers", customers);

		List<ProjectReportFrequency> projectReportFrequencys = projectReportFrequencyService
				.findAll();
		model.addAttribute("projectReportFrequencys", projectReportFrequencys);

		List<ProjectMemberType> projectMemberTypes = projectMemberTypeService.findAll();
		model.addAttribute("projectMemberTypes", projectMemberTypes);
		return "myProjects";
	}
	
	@RequestMapping(value = "/projectMembermgr")
	public String projectMembermgr(HttpServletRequest request,
			HttpServletResponse response, Model model) {

		List<People> persons = peopleService.findAll();
		model.addAttribute("persons", persons);

		List<Project> projects = projectService.findAll();
		model.addAttribute("projects", projects);

		List<ProjectMemberType> projectMemberTypes = projectMemberTypeService.findAll();
		model.addAttribute("projectMemberTypes", projectMemberTypes);

		List<People> createPersons = peopleService.findAll();
		model.addAttribute("createPersons", createPersons);
		return "projectMembermgr";
	}

	@RequestMapping(value = "/queryProjectMember")
	public String queryProjectMember(
			HttpServletRequest request,
			HttpServletResponse response,
			@RequestParam(value = "departmentId", defaultValue = "-1") Long departmentId,
			@RequestParam(value = "projectTypeId", defaultValue = "-1") Long projectTypeId,
			@RequestParam(value = "projectSourceId", defaultValue = "-1") Long projectSourceId,
			@RequestParam(value = "customerId", defaultValue = "-1") Long customerId,
			@RequestParam(value = "projectReportFrequencyId", defaultValue = "-1") Long projectReportFrequencyId,
			@RequestParam(value = "projectName", defaultValue = "") String projectName,
			@RequestParam(value = "status", defaultValue = "") String status,
			@RequestParam(value = "personId", defaultValue = "-1") Long personId,
			@RequestParam(value = "projectId", defaultValue = "-1") Long projectId,
			@RequestParam(value = "planEnterDateBegin", defaultValue = "") Date planEnterDateBegin,
			@RequestParam(value = "planEnterDateEnd", defaultValue = "") Date planEnterDateEnd,
			@RequestParam(value = "planExitDateBegin", defaultValue = "") Date planExitDateBegin,
			@RequestParam(value = "planExitDateEnd", defaultValue = "") Date planExitDateEnd,
			@RequestParam(value = "duty", defaultValue = "") String duty,
			@RequestParam(value = "projectMemberTypeId", defaultValue = "-1") Long projectMemberTypeId,
			@RequestParam(value = "createTimeBegin", defaultValue = "") Date createTimeBegin,
			@RequestParam(value = "createTimeEnd", defaultValue = "") Date createTimeEnd,
			@RequestParam(value = "createPersonId", defaultValue = "-1") Long createPersonId,
			@RequestParam(value = "remark", defaultValue = "") String remark,
			@RequestParam(value = "page", defaultValue = "1") Integer pageNumber,
			@RequestParam(value = "rows", defaultValue = "20") Integer pageSize,
			@RequestParam(value = "sort", defaultValue = "") String sort,
			@RequestParam(value = "order", defaultValue = "") String order,
			Model model) {
		Page<ProjectMember> projectMembers = projectMemberService.findAll(departmentId, projectTypeId, projectSourceId, customerId, projectReportFrequencyId,
				projectName, personId, projectId, status, planEnterDateBegin, planEnterDateEnd,
				planExitDateBegin, planExitDateEnd, duty, projectMemberTypeId,
				createTimeBegin, createTimeEnd, createPersonId, remark,
				pageNumber, pageSize, sort, order);
		JSONObject object = new JSONObject();
		object.put("total", projectMembers.getTotalElements());
		JSONArray models = new JSONArray();
		for (ProjectMember item : projectMembers) {
			JSONObject mod = new JSONObject();
			wrapData(item, mod);

			models.add(mod);
		}
		object.put("rows", models);
		PageJsonBean.printObject(response, object);
		return null;
	}
	
	@RequestMapping(value = "/findProjectMember")
	public String findProjectMember(
			HttpServletRequest request,
			HttpServletResponse response,
			@RequestParam(value = "id", defaultValue = "-1") Long id,
			Model model) {
		ProjectMember projectMember = projectMemberService.findOne(id);
		JSONObject object = new JSONObject();
		JSONObject mod = new JSONObject();
		wrapData(projectMember, mod);
		object.put("success", true);
		object.put("data", mod);
		PageJsonBean.printObject(response, object);
		return null;
	}

	private void wrapData(ProjectMember item, JSONObject mod) {
		mod.put("id", item.getId());
		mod.put("predictConsumeWorktime", NumberUtil.transition(item.getPredictConsumeWorktime()));
		
		Float actualConsumeWorktime = item.getActualConsumeWorktime();
		mod.put("actualConsumeWorktime", actualConsumeWorktime == null ? 0 : actualConsumeWorktime);
		mod.put("planEnterDate", com.rfid.project.util.DateUtil.dateTheDayToString(item.getPlanEnterDate()));
		mod.put("planExitDate", com.rfid.project.util.DateUtil.dateTheDayToString(item.getPlanExitDate()));
		mod.put("duty", item.getDuty() == null ? "" : item.getDuty());
		mod.put("worktimeRate", item.getWorktimeRate());
		mod.put("createTime", com.rfid.project.util.DateUtil.dateTheDayToString(item.getCreateTime()));
		mod.put("remark", com.rfid.project.util.StringUtil.getString(item.getRemark()));
		
		mod.put("personId", item.getPerson().getId());
		mod.put("personName", item.getPerson().getName());
		mod.put("projectId", item.getProject().getId());
		mod.put("projectName", item.getProject().getName());
		mod.put("projectMemberTypeId", item.getProjectMemberType().getId());
		mod.put("projectMemberTypeName", item.getProjectMemberType().getName());
		mod.put("createPersonId", item.getCreatePerson().getId());
		mod.put("createPersonName", item.getCreatePerson().getName());
	}

	@RequestMapping(value = "/queryMyProjects")
	public String queryMyProjects(
			HttpServletRequest request,
			HttpServletResponse response,
			@RequestParam(value = "departmentId", defaultValue = "-1") Long departmentId,
			@RequestParam(value = "projectTypeId", defaultValue = "-1") Long projectTypeId,
			@RequestParam(value = "projectSourceId", defaultValue = "-1") Long projectSourceId,
			@RequestParam(value = "customerId", defaultValue = "-1") Long customerId,
			@RequestParam(value = "projectReportFrequencyId", defaultValue = "-1") Long projectReportFrequencyId,
			@RequestParam(value = "projectName", defaultValue = "") String projectName,
			@RequestParam(value = "personId", defaultValue = "-1") Long personId,
			@RequestParam(value = "projectId", defaultValue = "-1") Long projectId,
			@RequestParam(value = "planEnterDateBegin", defaultValue = "") Date planEnterDateBegin,
			@RequestParam(value = "planEnterDateEnd", defaultValue = "") Date planEnterDateEnd,
			@RequestParam(value = "planExitDateBegin", defaultValue = "") Date planExitDateBegin,
			@RequestParam(value = "status", defaultValue = "") String status,
			@RequestParam(value = "planExitDateEnd", defaultValue = "") Date planExitDateEnd,
			@RequestParam(value = "duty", defaultValue = "") String duty,
			@RequestParam(value = "projectMemberTypeId", defaultValue = "-1") Long projectMemberTypeId,
			@RequestParam(value = "createTimeBegin", defaultValue = "") Date createTimeBegin,
			@RequestParam(value = "createTimeEnd", defaultValue = "") Date createTimeEnd,
			@RequestParam(value = "createPersonId", defaultValue = "-1") Long createPersonId,
			@RequestParam(value = "remark", defaultValue = "") String remark,
			@RequestParam(value = "page", defaultValue = "1") Integer pageNumber,
			@RequestParam(value = "rows", defaultValue = "20") Integer pageSize,
			@RequestParam(value = "sort", defaultValue = "") String sort,
			@RequestParam(value = "order", defaultValue = "") String order,
			Model model) {
		Page<ProjectMember> projectMembers = projectMemberService.findAll(departmentId, projectTypeId, projectSourceId, customerId, projectReportFrequencyId,
				projectName, personId, projectId, status, planEnterDateBegin, planEnterDateEnd,
				planExitDateBegin, planExitDateEnd, duty, projectMemberTypeId,
				createTimeBegin, createTimeEnd, createPersonId, remark,
				pageNumber, pageSize, sort, order);//"project.status", "asc"
		JSONObject object = new JSONObject();
		object.put("total", projectMembers.getTotalElements());
		JSONArray models = new JSONArray();
		for (ProjectMember projectMember : projectMembers) {
			Project project = projectMember.getProject();
			JSONObject mod = new JSONObject();
			mod.put("id", project.getId());
			mod.put("name", project.getName());
			mod.put("projectCode", project.getProjectCode());
			mod.put("createDate", com.rfid.project.util.DateUtil
					.dateTheDayToString(project.getCreateDate()));
			mod.put("startDate", com.rfid.project.util.DateUtil
					.dateTheDayToString(project.getStartDate()));
			mod.put("firstPlanFinishDate", com.rfid.project.util.DateUtil
					.dateTheDayToString(project.getFirstPlanFinishDate()));
			mod.put("planFinishDate", com.rfid.project.util.DateUtil
					.dateTheDayToString(project.getPlanFinishDate()));
			mod.put("planFinishDateChangeCount",
					project.getPlanFinishDateChangeCount());
			mod.put("actualFinishDate", com.rfid.project.util.DateUtil
					.dateTheDayToString(project.getActualFinishDate()));
			mod.put("projectDescription", project.getProjectDescription());
			mod.put("projectPlanNo", com.rfid.project.util.StringUtil.getString(project.getProjectPlanNo()));
			mod.put("projectBatchNo", com.rfid.project.util.StringUtil.getString(project.getProjectBatchNo()));
			mod.put("planConsumeWorkTime", project.getPlanConsumeWorkTime() == null ? 0 : project.getPlanConsumeWorkTime());
			mod.put("actualConsumeWorktime", project.getActualConsumeWorktime());
			mod.put("hardRate", project.getHardRate());

			mod.put("projectSourceID", project.getProjectSource().getId());
			mod.put("projectSourceName", project.getProjectSource().getName());

			mod.put("projectReportFrequencyID", project
					.getProjectReportFrequency().getId());
			mod.put("projectReportFrequencyName", project.getProjectReportFrequency().getName());

			mod.put("departmentID", project.getDepartment().getId());
			mod.put("departmentName", project.getDepartment().getName());

			mod.put("projectTypeID", project.getProjectType().getId());
			mod.put("projectTypeName", project.getProjectType().getName());

			mod.put("customerID", project.getCustomer().getId());
			mod.put("customerName", project.getCustomer().getName());
			mod.put("status", ProcessStatus.processStatusName(project.getStatus()));
			mod.put("statusCode", project.getStatus());
			
			mod.put("planConsumeWorkTime", project.getPlanConsumeWorkTime());
			Float sum = project.getActualConsumeWorktime();
			mod.put("actualConsumeWorktime", sum);
			float peopleAverage = 0;
			if(null != sum){
				peopleAverage = sum / 8;
			}
			mod.put("peopleAverage", com.rfid.project.util.StringUtil.getString(peopleAverage, ".", 3));

			models.add(mod);
		}
		object.put("rows", models);
		PageJsonBean.printObject(response, object);
		return null;
	}
	
	@RequestMapping(value = "/editProjectMembers", method = RequestMethod.POST)
	public String editProjectMembers(HttpServletRequest request,
			HttpServletResponse response, 
			@RequestParam(value = "projectId", defaultValue = "-1") Long projectId,
			@RequestParam(value = "personId", defaultValue = "") Long[] personIds,
			Model model, RedirectAttributes redirectAttributes) {
		JSONObject result = new JSONObject();
		boolean flag = true;
		
		try {
			projectMemberService.saveProjectMember(projectId, personIds, (People)request.getSession().getAttribute("currentUser"), ProjectMemberType.MEMBER);
		} catch (CannotUpdateException e) {
			flag = false;
			result.put("msg", e.getMessage());
		}
		
		result.put("success", flag);
		PageJsonBean.printObject(response, result);
		return null;
	}
	
	@RequestMapping(value = "/editProjectMember", method = RequestMethod.POST)
	public String editProjectMember(HttpServletRequest request,
			HttpServletResponse response, 
			@Valid ProjectMember projectMember,
			Model model, RedirectAttributes redirectAttributes) {
		JSONObject result = new JSONObject();
		boolean flag = true;
		People createPerson = projectMember.getCreatePerson();
		if(null == createPerson || null == createPerson.getId()){
			projectMember.setCreatePerson((People)request.getSession().getAttribute("currentUser"));
		}
		try {
			projectMemberService.saveProjectMember(projectMember);
		} catch (CannotUpdateException e) {
			flag = false;
			result.put("msg", e.getMessage());
		}
		result.put("success", flag);
		PageJsonBean.printObject(response, result);
		return null;
	}

	@RequestMapping(value = "/delProjectMembers")
	public String delProjectMembers(
			HttpServletRequest request, 
			HttpServletResponse response,
			@RequestParam(value = "projectId", defaultValue = "-1") Long projectId,
			@RequestParam(value = "personId", defaultValue = "") Long[] personIds) {
		JSONObject result = new JSONObject();
		boolean flag = true;
		this.projectMemberService.deleteProjectMembers(projectId, personIds);
		result.put("success", flag);
		PageJsonBean.printObject(response, result);
		return null;
	}
	
	@RequestMapping(value = "/delProjectMember")
	public String delProjectMember(
			HttpServletRequest request, 
			HttpServletResponse response,
			@RequestParam(value = "id", defaultValue = "") Long id) {
		JSONObject result = new JSONObject();
		boolean flag = true;
		try {
			this.projectMemberService.deleteProjectMembers(id);
		} catch (CannotDelException e) {
			flag = false;
			result.put("msg", e.getMessage());
		}
		result.put("success", flag);
		PageJsonBean.printObject(response, result);
		return null;
	}

	@RequestMapping(value = "/queryProjectMemebers")
	public String queryProjectMemebers(
			HttpServletRequest request,
			HttpServletResponse response, 
			@Valid Project project, 
			Model model){
		/*
		Page<People> peoples = peopleService.findAll(name, personalTel,
				departmentId, gender, officeTel, remark, positionId,
				technicalTitleId, username, password, pageNumber, pageSize,
				sort, order);
		*/
		ProjectMemberType projectMemberType = new ProjectMemberType();
		projectMemberType.setId(ProjectMemberType.MEMBER);
		Set<People> peoples = this.projectMemberService.findPeoplesByProject(project, projectMemberType);
		JSONObject object = new JSONObject();
		//object.put("total", peoples.getTotalElements());
		object.put("total", peoples.size());
		JSONArray models = new JSONArray();
		for (People people : peoples) {
			JSONObject mod = new JSONObject();
			mod.put("id", people.getId());
			mod.put("name", people.getName());
			mod.put("personalTel", people.getPersonalTel());
			mod.put("departmentId", people.getDepartment().getId());
			mod.put("departmentName", people.getDepartment().getName());
			mod.put("gender", people.getGender());
			mod.put("officeTel", people.getOfficeTel());
			mod.put("remark", people.getRemark());
			mod.put("positionId", people.getPosition().getId());
			mod.put("positionName", people.getPosition().getName());
			mod.put("technicalTitleId", people.getTechnicalTitle().getId());
			mod.put("technicalTitleName", people.getTechnicalTitle().getName());
			mod.put("username", people.getUsername());
			mod.put("password", people.getPassword());
			
			models.add(mod);
		}
		object.put("rows", models);
		PageJsonBean.printObject(response, object);
		return null;
	}
	@RequestMapping(value = "/queryProjectManagerMemebers")
	public String queryProjectManagerMemebers(
			HttpServletRequest request,
			HttpServletResponse response, 
			@Valid Project project, 
			Model model){
		/*
		Page<People> peoples = peopleService.findAll(name, personalTel,
				departmentId, gender, officeTel, remark, positionId,
				technicalTitleId, username, password, pageNumber, pageSize,
				sort, order);
		 */
		ProjectMemberType projectMemberType = new ProjectMemberType();
		projectMemberType.setId(ProjectMemberType.MANAGER);
		Set<People> peoples = this.projectMemberService.findPeoplesByProject(project, projectMemberType);
		JSONObject object = new JSONObject();
		//object.put("total", peoples.getTotalElements());
		object.put("total", peoples.size());
		JSONArray models = new JSONArray();
		for (People people : peoples) {
			JSONObject mod = new JSONObject();
			mod.put("id", people.getId());
			mod.put("name", people.getName());
			mod.put("personalTel", people.getPersonalTel());
			mod.put("departmentId", people.getDepartment().getId());
			mod.put("departmentName", people.getDepartment().getName());
			mod.put("gender", people.getGender());
			mod.put("officeTel", people.getOfficeTel());
			mod.put("remark", people.getRemark());
			mod.put("positionId", people.getPosition().getId());
			mod.put("positionName", people.getPosition().getName());
			mod.put("technicalTitleId", people.getTechnicalTitle().getId());
			mod.put("technicalTitleName", people.getTechnicalTitle().getName());
			mod.put("username", people.getUsername());
			mod.put("password", people.getPassword());
			
			models.add(mod);
		}
		object.put("rows", models);
		PageJsonBean.printObject(response, object);
		return null;
	}
	@RequestMapping(value = "/queryCommonPeoples")
	public String queryCommonPeoples(
			HttpServletRequest request,
			HttpServletResponse response,
			@RequestParam(value = "name", defaultValue = "") String name,
			@RequestParam(value = "personalTel", defaultValue = "") String personalTel,
			@RequestParam(value = "departmentId", defaultValue = "-1") Long departmentId,
			@RequestParam(value = "projectId", defaultValue = "-1") Long projectId,
			@RequestParam(value = "gender", defaultValue = "") String gender,
			@RequestParam(value = "officeTel", defaultValue = "") String officeTel,
			@RequestParam(value = "remark", defaultValue = "") String remark,
			@RequestParam(value = "positionId", defaultValue = "-1") Long positionId,
			@RequestParam(value = "technicalTitleId", defaultValue = "-1") Long technicalTitleId,
			@RequestParam(value = "username", defaultValue = "") String username,
			@RequestParam(value = "password", defaultValue = "") String password,
			@RequestParam(value = "page", defaultValue = "-1") Integer pageNumber,
			@RequestParam(value = "rows", defaultValue = "-1") Integer pageSize,
			@RequestParam(value = "sort", defaultValue = "") String sort,
			@RequestParam(value = "order", defaultValue = "") String order,
			Model model){
		/*
		Page<People> peoples = peopleService.findAll(name, personalTel,
				departmentId, gender, officeTel, remark, positionId,
				technicalTitleId, username, password, pageNumber, pageSize,
				sort, order);
		*/
		List<People> peoples = this.peopleService.findAll(name, personalTel, departmentId, gender, officeTel, remark, positionId, technicalTitleId, username, password, projectId, null);
		JSONObject object = new JSONObject();
		//object.put("total", peoples.getTotalElements());
		object.put("total", peoples.size());
		JSONArray models = new JSONArray();
		for (People people : peoples) {
			JSONObject mod = new JSONObject();
			mod.put("id", people.getId());
			mod.put("name", people.getName());
			mod.put("personalTel", people.getPersonalTel());
			mod.put("departmentId", people.getDepartment().getId());
			mod.put("departmentName", people.getDepartment().getName());
			mod.put("gender", people.getGender());
			mod.put("officeTel", people.getOfficeTel());
			mod.put("remark", people.getRemark());
			mod.put("positionId", people.getPosition().getId());
			mod.put("positionName", people.getPosition().getName());
			mod.put("technicalTitleId", people.getTechnicalTitle().getId());
			mod.put("technicalTitleName", people.getTechnicalTitle().getName());
			mod.put("username", people.getUsername());
			mod.put("password", people.getPassword());
			
			models.add(mod);
		}
		object.put("rows", models);
		PageJsonBean.printObject(response, object);
		return null;
	}
	@InitBinder
	protected void initBinder(HttpServletRequest request,
			ServletRequestDataBinder binder) throws Exception {
		DateFormat dateFormat = com.rfid.project.util.DateUtil.getFormat("yyyy-MM-dd");
		dateFormat.setLenient(false);
		binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
	}

}
